%{
    This file is part of StemCellQC, a video bioinformatics software
    toolkit for analysis of phase contrast microscopy videos.
    Copyright 2013-2015 Vincent On. [vincenton001-at-gmail.com]

    StemCellQC is free software: you can redistribute it and/or 
    modify it under the terms of the GNU General Public License as 
    published by the Free Software Foundation, either version 3 of the 
    License, or (at your option) any later version.

    StemCellQC is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with StemCellQC.  If not, see <http://www.gnu.org/licenses/>.
%}

% function used to extract intensity information from image

function [avg_intensity, max_intensity, min_intensity, bright_area] = intensity_extract( index, seg, area_thres ) 
global mov

for i = 1 : 5
    temp = bwmorph(seg,'remove');
    seg(temp ~= 0 ) = 0;
end

%normalize image
temp = double(mov(index).data) - min(min( double(mov(index).data) ));
temp = temp ./ max(max( temp ));

%bg mean
bg = temp;
bg( seg ~= 0 ) = NaN;
bg_int = nanmean(nanmean( bg ));

%get silhouette image
sil = temp;
sil(seg == 0) = 0;

%calculate mean value of the silhouette
temp = double(sil);
region_val = sil(seg ~= 0);
avg_intensity = nanmean( region_val )*255;
max_intensity = nanmax( region_val )*255;
min_intensity = nanmin( region_val )*255;


bright_thres = bg_int + .15; %30
bright_roof = bg_int + .30;

bright_region = sil;
bright_region(sil>=bright_thres) = 1;
bright_region(sil<bright_thres) = 0;
bright_region(sil>=bright_roof) = 0;

bright_region = logical(bright_region);

%find connected regions
bright_region = bwlabel(bright_region);

bright_region = bwareaopen( bright_region, area_thres );

bright_region = double(bright_region);

bright_area = nnz( bright_region );
